package com.qifan.energy.netWork;

import com.qifan.energy.mvp.callback.IHttpListener;
import com.qifan.energy.global.Constant;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author : FangShiKang
 * @date : 2020/04/11.
 * email : fangshikang@outlook.com
 * desc :   Retrofit网络请求的工具类
 */
public class RetrofitManager {

    //域名
    private final String BASE_URL = Constant.BaseUrl8085;

    private static RetrofitManager manager;

    private ObservedApi mObservedApi;

    private Observer mMObserver;

    //单例模式
    public static synchronized RetrofitManager getInstance() {
        if (manager == null) {
            manager = new RetrofitManager();
        }
        return manager;
    }

    private RetrofitManager() {
        //日志拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //获取 builder对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.writeTimeout(15, TimeUnit.SECONDS);//写入超时
        builder.readTimeout(15, TimeUnit.SECONDS);//读取超时
        builder.connectTimeout(15, TimeUnit.SECONDS);//连接超时
        //builder.addNetworkInterceptor(interceptor);//添加拦截器(调试用)
        builder.addInterceptor(interceptor);
        builder.retryOnConnectionFailure(true);
        //获取 client 对象
        OkHttpClient client = builder.build();
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .client(client)
                .build();
        mObservedApi = retrofit.create(ObservedApi.class);
    }

    public Map<String, RequestBody> generateRequestBody(Map<String, String> requestDataMap) {
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        for (String kay : requestDataMap.keySet()) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                    requestDataMap.get(kay) == null ? "" : requestDataMap.get(kay));
            requestBodyMap.put(kay, requestBody);
        }
        return requestBodyMap;
    }


    /**
     * get请求
     * @param url
     * @return
     */
    public RetrofitManager retrofitGet(String url, IHttpListener mHttpListener) {
        mObservedApi.get(url)
                .subscribeOn(Schedulers.io())//后台执行在哪个线程
                .observeOn(AndroidSchedulers.mainThread())//最终完成后执行在哪个线程
                .subscribe(getObserver(mHttpListener));//设置我们的    RxJava
        return manager;
    }


    /**
     * 普通post请求
     * @param url
     * @param map
     * @return
     */
    public RetrofitManager retrofitPost(String url, Map<String, String> map, IHttpListener mHttpListener) {
        //判断,当map为空的时候,重新创建一个   HashMap
        if (map == null) {
            map = new HashMap<>();
        }
        mObservedApi.post(url, map)//post请求
                .subscribeOn(Schedulers.io())//后台执行在哪个线程
                .observeOn(AndroidSchedulers.mainThread())//最终完成后执行在哪个线程
                .subscribe(getObserver(mHttpListener));//设置我们的    RxJava
        return manager;
    }

    /**
     * 表单post请求
     * @param url
     * @param map
     * @return
     */
    public RetrofitManager retrofitPostFormBody(String url, Map<String, RequestBody> map, IHttpListener mHttpListener) {
        //判断,当map为空的时候,重新创建一个   HashMap
        if (map == null) {
            map = new HashMap<>();
        }
        mObservedApi.postFormBody(url, map)//postFormBody请求
                .subscribeOn(Schedulers.io())//后台执行在哪个线程
                .observeOn(AndroidSchedulers.mainThread())//最终完成后执行在哪个线程
                .subscribe(getObserver(mHttpListener));//设置我们的    RxJava
        return manager;
    }



    /**
     * 头像上传
     *
     * @param url
     * @param params
     * @param callBack
     */
    public void postImages(String url, Map<String, RequestBody> params, IHttpListener callBack) {
        if (params == null) {
            params = new HashMap<>();
        }
        mObservedApi.postFormBody(url, params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver(callBack));
    }

    /**
     * 创建观察者模式
     */
    private Observer getObserver(final IHttpListener mHttpListener) {

        mMObserver = new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    String data = responseBody.string();// TODO: 注意： 这里是string(),不是toString()!!!
                    if (mHttpListener != null) {
                        mHttpListener.onSuccess(data);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if (mHttpListener != null) {
                        mHttpListener.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                if (mHttpListener != null) {
                    mHttpListener.onFailed(e.getMessage());
                }
            }

            @Override
            public void onComplete() {

            }

        };
        return mMObserver;
    }

    /* 获取ObservedApi */
    public ObservedApi getObservedApi(){
        return mObservedApi;
    }

    //声明接口
    private IHttpListener mHttpListener;

    //set方法
    public void setHttpListener(IHttpListener httpListener) {
        mHttpListener = httpListener;
    }
}
